<template>
  <div>
    <a-modal title="添加sku" :visible="visible" @before-open="open" @cancel="handleCancel" :align-center="false" title-align="start" width="1000px" :mask-closable="false">
      <a-space>
        <a-select placeholder="请选择SKU编码规格" v-model="autoCreateType" :style="{ width: '310px' }">
          <a-option label="SPU-规格值标识（例如：AB0001-R-XL）" value="1"></a-option>
          <a-option label="SPU-自增数字（例如：AB0001-1）" value="2"></a-option>
        </a-select>
        <a-button class="gray-outline" @click="createSku">按规格生成SKU</a-button>
        <a-button class="gray-outline" @click="batchDelTableItem">批量移除</a-button>
      </a-space>

      <a-table size="mini" class="table-two-line mt10" row-key="onlyKey" :pagination="false" v-model:selectedKeys="selIndexs" :row-selection="{ type: 'checkbox', showCheckedAll: true, width: 40 }" :bordered="{ cell: true }" :scroll="{ y: 350, x: 1160 }" :data="autoCreateList">
        <template #columns>
          <a-table-column title="序号" #cell="{ record, rowIndex }" :width="50">{{ rowIndex + 1 }}</a-table-column>
          <a-table-column title="规格">
            <a-table-column v-for="(item, index) of titleColumnArr" :key="index" :title="item.nameCn" :width="120">
              <template #cell="{ record }">
                {{ record.specValueList.find((e: any) => e.nameCn == item.nameCn).valueCn }}
              </template>
            </a-table-column>
          </a-table-column>
          <a-table-column title="图片" #cell="{ record, rowIndex }" :width="60">
            <UplaodImg :limit="1" v-model="record.skuImg" />
          </a-table-column>
          <a-table-column title="产品SKU" #cell="{ record, rowIndex }" :width="240">
            <a-space style="width: 100%">
              <a-input v-model="record.sku" :style="{ flex: 1 }" :disabled="record.isSelOldSku" />
              <a-button v-if="record.isSelOldSku" size="small" class="gray-outline" @click="restoreItemData(record)">
                <template #icon>
                  <icon-close style="font-size: 18px" />
                </template>
              </a-button>

              <a-popover v-model:popup-visible="record.showSetOldSkuPopup" trigger="click">
                <a-button v-if="!record.isSelOldSku" size="small" class="gray-outline">
                  <template #icon>
                    <icon-plus style="font-size: 18px" />
                  </template>
                </a-button>
                <template #content>
                  <a-input-search @search="handleSearch" @press-enter="handleSearch" allow-clear v-model="skuSearchVal" placeholder="请输入sku选择产品" />

                  <a-scrollbar style="max-height: 200px; overflow: auto; margin-top: 10px">
                    <div>
                      <a-empty v-if="skuOptions.length <= 0" description="请输入SKU搜索" />
                      <div v-else>
                        <div class="sku-item cursor" @click="selSkuCurIndex = index" :class="[index == selSkuCurIndex ? 'sku_active' : '']" v-for="(item, index) of skuOptions" :key="index">
                          <a-space>
                            <div>
                              <ImgPopover :src="imgUrl(item)">
                                <template #con>
                                  <a-image :preview="false" width="40" height="40" fit="contain" :src="imgUrl(item)" />
                                </template>
                              </ImgPopover>
                            </div>
                            <div>
                              <div>{{ item.sku }}</div>
                              <div>{{ $extract(item, 'category.name') }}</div>
                            </div>
                          </a-space>
                        </div>
                      </div>
                    </div>
                  </a-scrollbar>

                  <div class="popup-footer">
                    <a-button size="mini" class="gray-outline" @click="record.showSetOldSkuPopup = false">取消</a-button>
                    <a-button size="mini" class="ml10" type="primary" @click="setSkuOldValToItem(record)">确认</a-button>
                  </div>
                </template>
              </a-popover>
            </a-space>
          </a-table-column>
          <a-table-column title="产品名称" #cell="{ record, rowIndex }" :width="140">
            <a-space>
              <a-input v-model="record.skuName" :disabled="record.isSelOldSku" allow-clear />
              <a-button size="small" class="gray-outline" @click="setGloablePro('skuName', record, rowIndex)">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </a-space>
          </a-table-column>
          <a-table-column title="重量(g)" #cell="{ record, rowIndex }" :width="140">
            <a-space>
              <a-input-number v-model="record.weightNum" hide-button :disabled="record.isSelOldSku" />
              <a-button size="small" class="gray-outline" @click="setGloablePro('weightNum', record, rowIndex)">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </a-space>
          </a-table-column>
          <a-table-column title="体积(cm)" #cell="{ record, rowIndex }" :width="240">
            <a-space>
              <a-input-number v-model="record.lengthNum" placeholder="长" hide-button :disabled="record.isSelOldSku" />
              <a-input-number v-model="record.widthNum" placeholder="宽" hide-button :disabled="record.isSelOldSku" />
              <a-input-number v-model="record.heightNum" placeholder="高" hide-button :disabled="record.isSelOldSku" />
              <a-button size="small" class="gray-outline" @click="setGloablePro('volume', record, rowIndex)">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </a-space>
          </a-table-column>
          <a-table-column title="销售员" #cell="{ record, rowIndex }" :width="200">
            <a-space>
              <a-select class="second" v-model="record.salerIdList" :style="{ width: '140px' }" :max-tag-count="1" allow-search allow-clear multiple placeholder="请选择">
                <a-option :label="item.userName" :value="item.id" v-for="item of userList"></a-option>
              </a-select>
              <a-button size="small" class="gray-outline" @click="setGloablePro('salers', record, rowIndex)">
                <template #icon>
                  <icon-double-down />
                </template>
              </a-button>
            </a-space>
          </a-table-column>
          <a-table-column title="操作" :width="60" #cell="{ record, rowIndex }" fixed="right">
            <a-button class="gray-outline" size="mini" @click="autoCreateList.splice(rowIndex, 1)">
              <icon-minus />
            </a-button>
          </a-table-column>
        </template>
      </a-table>

      <template #footer>
        <a-button class="gray-outline" @click="handleCancel">取消</a-button>
        <a-button type="primary" :loading="loading" class="ml10" @click="handleOk">确认</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs, computed } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { getArrayByArrays } from '@/utils'
  import { getProductSKUList } from '@/api/product'
  import UplaodImg from '@/components/uploadImg.vue'
  import { arraysAreEqual } from '@/utils/index'
  import _ from 'lodash-es'
  export default defineComponent({
    props: ['specList', 'tableList', 'spu', 'userList'],
    components: { UplaodImg },
    setup(props: any, { emit }) {
      let visible = ref(false)
      const data: any = reactive({
        loading: false,
        autoCreateType: '1',
        selIndexs: [],
        autoCreateList: [],
        titleColumnArr: [],
        skuSearchVal: '',
        skuOptions: [],
        skuListLoading: false,
        showSetOldSkuPopup: false,
        lastCreateSkuList: [],
        selSkuCurIndex: 0,
      })

      const open = () => {
        data.autoCreateList = []
        createSku()
      }
      const handleOk = () => {
        let arr: any = []
        data.selIndexs.forEach((e: any) => {
          let item: any = data.autoCreateList.find((el: any) => e == el.onlyKey)
          if (item) arr.push(_.cloneDeep(item))
        })
        emit('save', arr)
        data.selIndexs = []
        visible.value = false
      }
      const handleCancel = () => {
        visible.value = false
      }
      const createSku = async () => {
        let arr: any = []
        let curTableData: any = []
        data.autoCreateList = []
        props.specList.forEach((e: any) => {
          e.valueList.map((el: any) => {
            el.nameCn = e.nameCn
            el.nameEn = e.nameEn
            el.specId = e.id
            return e
          })
          let newArr = e.valueList.filter((el: any) => el.checked)
          arr.push(newArr)
        })
        let createArr = getArrayByArrays(arr.filter((e: any) => e.length > 0))
        createArr.forEach((e: any, index: number) => {
          let str = e.map((el: any) => el.valueCode).join('-')

          let obj = {
            onlyKey: index + 1,
            skuImg: '',
            sku: data.autoCreateType == '1' ? `${props.spu}-${str}` : `${props.spu}-${index + 1}`,
            skuName: '',
            specValueList: e,
            weightNum: '',
            heightNum: '',
            lengthNum: '',
            widthNum: '',
            weight: {
              unit: 'g',
              weight: 0,
            },
            volume: {
              height: 0,
              length: 0,
              unit: 'cm',
              width: 0,
            },
            salerIdList: [],
            specFlag: '',
            status: 'ACTIVE',
          }
          curTableData.push(obj)
        })
        // data.autoCreateList = curTableData
        // console.log(curTableData)

        // // 和之前的数据对比，相同的不显示
        comparisonTableData(curTableData, props.tableList)
        // // 重新保存最新的数据，用作对比
        data.lastCreateSkuList = curTableData
        // 每次重新生成表格标题
        data.titleColumnArr = createArr[0]
      }

      // 比对两次数据，删除掉相同规格的数据
      const comparisonTableData = (newArr?: any, oldArr?: any) => {
        let oldData = _.cloneDeep(oldArr)
        newArr.forEach((e: any) => {
          let flag = false
          for (let i = 0; i < oldData.length; i++) {
            const el = oldData[i]
            let arr1 = _.cloneDeep(e.specValueList)
            let arr2 = _.cloneDeep(el?.specValueList || [])
            flag = arraysAreEqual(arr1, arr2, 'valueCn')
            if (flag) break
          }
          if (!flag) {
            data.autoCreateList.push(e)
          }
        })

        let oldData1 = _.cloneDeep(data.lastCreateSkuList)
        data.autoCreateList.forEach((e: any) => {
          oldData1.forEach((el: any) => {
            let arr1 = _.cloneDeep(e.specValueList)
            let arr2 = _.cloneDeep(el?.specValueList || [])
            if (arraysAreEqual(arr1, arr2, 'valueCn')) {
              let newObj = _.cloneDeep(el)
              delete newObj.specValueList
              delete newObj.sku
              e = Object.assign(e, newObj)
            }
          })
        })
      }

      const batchDelTableItem = () => {
        if (!data.selIndexs[0]) {
          return Message.error('请勾选需要删除的数据')
        }
        let arr: any = []
        data.autoCreateList.forEach((el: any) => {
          let index = data.selIndexs.findIndex((e: any) => el.onlyKey == e)
          if (index == -1) {
            arr.push(el)
          }
        })
        data.autoCreateList = arr
        data.selIndexs = []
      }

      const handleSearch = async (value: string) => {
        data.selSkuCurIndex = 0
        if (value) {
          try {
            data.skuListLoading = true
            let params = {
              searchType: 'fuzzy',
              keywordType: 'sku',
              keyword: value,
            }
            const res: any = await getProductSKUList(params)
            data.skuOptions = res?.data?.records || []
          } catch (error) {}
          data.skuListLoading = false
        } else {
          data.skuOptions = []
        }
      }

      const setSkuOldValToItem = (item: any) => {
        // if (!data.skuSearchVal) {
        //   return (item.showSetOldSkuPopup = false)
        // }
        let info: any = data.skuOptions[data.selSkuCurIndex]

        let salers = info?.salerList || []
        let picArr = info?.productPicList || []
        if (info) {
          item.isSelOldSku = true
          item.heightNum = info?.volume?.height || ''
          item.widthNum = info?.volume?.width || ''
          item.lengthNum = info?.volume?.length || ''
          item.weightNum = info?.weight?.weight || ''
          item.salerIdList = salers.map((e: any) => e.id)
          item.oldSku = item.sku
          item.sku = info.sku
          item.oldSkuName = item.skuName
          item.skuName = info.skuName
          item.skuImg = picArr[0] ? picArr[0].url : ''
          item.id = info.id
        }
        item.showSetOldSkuPopup = false
        data.skuSearchVal = ''
      }

      const restoreItemData = (item: any) => {
        item.heightNum = ''
        item.widthNum = ''
        item.lengthNum = ''
        item.weightNum = ''
        item.sku = item.oldSku
        item.skuName = item.oldSkuName
        item.salerIdList = []
        item.isSelOldSku = false
      }

      const setGloablePro = (name: string, item: any, index: number) => {
        if (name == 'skuName') {
          data.autoCreateList.forEach((e: any, i: number) => {
            if (i > index) {
              e.skuName = item.skuName
            }
          })
        } else if (name == 'weightNum') {
          data.autoCreateList.forEach((e: any, i: number) => {
            if (i > index) {
              e.weightNum = item.weightNum
            }
          })
        } else if (name == 'volume') {
          data.autoCreateList.forEach((e: any, i: number) => {
            if (i > index) {
              e.heightNum = item.heightNum
              e.widthNum = item.widthNum
              e.lengthNum = item.lengthNum
            }
          })
        } else if (name == 'salers') {
          console.log(item.salerIdList)

          data.autoCreateList.forEach((e: any, i: number) => {
            if (i > index) {
              e.salerIdList = item.salerIdList
            }
          })
        }
      }

      const imgUrl = (info: any) => {
        let arr = info?.productPicList || []
        return arr[0] ? arr[0].url : ''
      }

      return {
        ...(toRefs(data) as any),
        visible,
        open,
        handleOk,
        handleCancel,
        batchDelTableItem,
        createSku,
        handleSearch,
        setSkuOldValToItem,
        restoreItemData,
        setGloablePro,
        imgUrl,
      }
    },
  })
</script>

<style lang="less" scoped>
  .sku-item {
    width: 100%;
    height: 50px;
    padding: 5px;
    border: 1px solid #d7d7d7;
    margin-top: 10px;
    border-radius: 5px;
  }

  .sku_active {
    border: 1px solid rgb(var(--primary-6));
  }

  :deep(.arco-upload-list-picture-operation) {
    line-height: 40px;
  }
  :deep(.arco-upload-picture-card) {
    min-width: 40px !important;
    width: 40px !important;
    height: 40px !important;
  }
  :deep(.arco-upload-list-picture) {
    width: 40px !important;
    height: 40px !important;
  }
  .popup-footer {
    text-align: right;
    margin-top: 5px;
  }
</style>
